<template>
    <!-- 测试页面，先用flex布局 -->
    <section class="dynamic-form-create" :style="{height:this.elHeight}">
        <div class="main">
            <div class="left">
                <DynamicForm ref="form" :_config="config" design @init="init" :key="dFormKey"/>
            </div>
            <div class="right">
                <el-button-group class="operate-list">
                    <el-button type="primary" @click="addField">新增</el-button>
                    <el-button type="primary" @click="downloadConfig">保存配置</el-button>
                    <el-button type="primary" @click="setConfig">导入配置</el-button>
                </el-button-group>
                <el-form v-if="isFormConfigInit" label-position="top" size="mini">
                    <el-tabs v-model="ctrlTabName">
                        <el-tab-pane label="字段配置" name="field">
                            <FieldCtrl v-if="activeField" :field="activeField" :key="activeRandomCode"/>
                        </el-tab-pane>
                        <el-tab-pane label="表单配置" name="form">
                            <FormCtrl v-if="isFormConfigInit" :form="config.form"/>
                        </el-tab-pane>
                        <el-tab-pane label="请求配置" name="request">
                            <RequestCtrl/>
                        </el-tab-pane>
                    </el-tabs>
                </el-form>
            </div>
        </div>
    </section>
</template>

<script>
    import DynamicForm from '../dynamic-form/index.vue'
    import FormCtrl from './FormCtrl'
    import FieldCtrl from './FieldCtrl'
    import RequestCtrl from './RequestCtrl'

    const js2jscode = (function () {
        function main(target) {
            const targetType = Object.prototype.toString.call(target).match(/\[object\s(.*?)]/)[1]
            let code = ''
            switch (targetType) {
                case 'Object':
                    code += '{'
                    for (let k in target) {
                        code += `${k}: ${main(target[k])},`
                    }
                    if (code.length > 1) {
                        code = code.slice(0, -1)
                    }
                    code += '}'
                    break
                case 'Array':
                    code += '['
                    for (let i = 0; i < target.length; i++) {
                        code += `${main(target[i])},`
                    }
                    if (code.length > 1) {
                        code = code.slice(0, -1)
                    }
                    code += ']'
                    break
                case 'Function':
                    code = target.toString()
                    if (code[0] !== 'f' && code[1] !== 'u') {
                        code = 'function ' + code
                    }
                    code = code.replace(/\[native\scode\]/, '/* 你的代码 */')
                    break
                case 'String':
                    code = `'${target}'`
                    break
                case 'Number':
                case 'Boolean':
                    code = target
                    break
            }
            return code || JSON.stringify(target)
        }

        return function js2jscode(any) {
            return main(any)
        }
    })()

    export default {
        components: {
            DynamicForm,
            FormCtrl,
            FieldCtrl,
            RequestCtrl,
        },
        provide() {
            return {
                desForm: this,
                config: this.config,
            }
        },
        data() {
            this.isFormConfigInit = false
            this.dForm = null
            this.elHeight = 'auto'

            return {
                dFormKey: 0,
                config: {
                    // 声明需要用到的数据（这些是响应式）
                    cancel: {},

                    edit: {
                        url: {},
                    },
                    create: {
                        url: {},
                    },

                    form: {
                        style: {},
                        props: {},
                    },
                    parts: [
                        {
                            fields: [],
                        },
                    ],
                },
                ctrlTabName: 'field',
                activeRandomCode: 0,
                activeField: null,
            }
        },
        methods: {
            init() {
                this.isFormConfigInit = true
                this.$forceUpdate()
            },
            addField() {
                let id = (Date.now() + '').slice(8) // 13 - 8
                this.config.parts[0].fields.push({
                    block: false,
                    scope: false, // 仅嵌套模式有效
                    size: 24,
                    required: true,
                    label: '字段名' + id,
                    model: '字段数据' + id,
                    component: {
                        type: 'el-input',
                    },
                })
            },
            downloadConfig() {
                console.log(js2jscode(this.config))
            },
            setConfig() {
                let config = null
                this.$msgbox({
                    title: '粘贴你的配置',
                    message: <div>
                        <el-input type="textarea" rows={8} onInput={val => config = val}/>
                    </div>,
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    try {
                        config = eval('config=' + config)
                        this.$set(this, 'config', config)
                        this.dFormKey++
                    } catch (e) {
                    }
                    config = null
                }).catch(function () {

                })
            },
        },
        mounted() {
            this.dForm = this.$refs['form']
            this.elHeight = this.$parent.$el.offsetHeight - 40 + 'px'

            // # end
            this.$forceUpdate()

            //
            this.$on('active-change', field => {
                this.activeRandomCode++
                this.activeField = field
            })
        },
    }
</script>

<style lang="scss" scoped>
    .dynamic-form-create {
        box-sizing: border-box;
        position: relative;
        padding: 0;
    }


    .main {
        box-sizing: border-box;
        display: flex;
        height: 100%;

        .left {
            overflow-y: auto;
            flex: 1;
        }

        .right {
            overflow-y: auto;
            /*padding-top: 20px;*/
            width: 300px;
            min-width: 300px;

            .operate-list {
                display: block;
                width: 100%;
                text-align: right;
            }
        }
    }

    /deep/ {
        .dynamic-form-item-wrapper {
            .el-form-item {
                border: 1px dashed #c8ebfb;
            }

            &.active .el-form-item {
                background-color: #c8ebfb;
            }
        }
    }
</style>
